package com.mgg.auth.service;

import com.mgg.auth.AuthUser;
import com.mgg.common.dao.DaoSupport;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: lijun
 * @Date: 2018/9/3 21:18
 */
@Component
public class AdminUserDetailsService implements UserDetailsService{

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DaoSupport dao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户名:" + username);
        try {
            Map<String,Object> adminUserMap = dao.findForObject("AuthMapper.getAdminUserInfoByUsername",username);
            if (MapUtils.isEmpty(adminUserMap)) {
                throw new UsernameNotFoundException("用户不存在");
            }
            String uid = adminUserMap.get("uid").toString();
            String password  = (String) adminUserMap.get("password");
            password = passwordEncoder.encode(password);
            Boolean expired = (Boolean) adminUserMap.get("is_expired");
            Boolean locked = (Boolean) adminUserMap.get("is_locked");
            Boolean deleted = (Boolean) adminUserMap.get("is_deleted");
            return new AuthUser(uid,username,password,!deleted,!expired,!expired,!locked,
                    AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ANONYMOUS"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("用户查询失败");
        }
    }
}
